package com.flyxiaozhu.rabbitmqdemo;

import com.rabbitmq.client.Channel;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.stereotype.Component;

import java.io.IOException;

@Component
/**
 * 消费者
 */
public class Receiver {
    //  ---------------- direct 形式 -------------------
    @RabbitListener(queues = "direct-queue-1")
    public void directReceiver1(Message msg, Channel channel) throws IOException {
        System.out.println("[direct] Test 1 - receiver1:" + new String(msg.getBody()));
        channel.basicAck(msg.getMessageProperties().getDeliveryTag(), true);
    }

    @RabbitListener(queues = "direct-queue-2")
    public void directReceiver2(Message msg, Channel channel) throws IOException {
        System.out.println("[direct] Test 1 - receiver2:" + new String(msg.getBody()));
        //模拟出现异常
        try {
            if (true) {
                System.out.println("[direct] Test 1 - receiver2: 抛异常了");
                throw new IOException("抛异常了!");
            }
        } catch (Exception e) {
            channel.basicNack(msg.getMessageProperties().getDeliveryTag(), false, false);
        }
    }

//    @RabbitListener(queues = "direct-queue-2")
//    public void directReceiver3(String msg) {
//        System.out.println("[direct] Test 2 - receiver3:" + msg);
//    }

    //  ---------------- fanout 形式 -------------------
    @RabbitListener(queues = "#{fanoutQueue1.name}")
    public void fanoutReceiver1(String msg) {
        System.out.println("[fanout] receiver1:" + msg);
    }

    @RabbitListener(queues = "#{fanoutQueue2.name}")
    public void fanoutReceiver2(String msg) {
        System.out.println("[fanout] receiver2:" + msg);
    }

    //  ---------------- topic 形式 -------------------
    @RabbitListener(queues = "topic.queue-1")
    public void topicReceiver1(String msg) {
        System.out.println("[topic] receiver1:" + msg);
    }

    @RabbitListener(queues = "topic.queue-2")
    public void topicReceiver2(String msg) {
        System.out.println("[topic] receiver2:" + msg);
    }
}
